<template>
  <div class="order-management-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入物流单号"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-select
          v-model="statusFilter"
          placeholder="请选择订单状态"
          size="small"
          style="width: 150px; margin-left: 10px;"
          clearable
        >
          <el-option label="全部状态" :value="''"></el-option>
          <el-option label="生产中" :value="1">
            <el-tag type="warning" size="mini">生产中</el-tag>
          </el-option>
          <el-option label="已发货" :value="2">
            <el-tag type="primary" size="mini">已发货</el-tag>
          </el-option>
          <el-option label="已签收" :value="3">
            <el-tag type="success" size="mini">已签收</el-tag>
          </el-option>
        </el-select>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 订单列表表格 -->
    <el-table 
      :data="orderList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" label="订单ID" width="80px" align="center"></el-table-column> -->
       <el-table-column label="设备信息" width="120px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.devices">{{ scope.row.devices.device_name }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="配件信息" width="250px" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.accessories && scope.row.accessories.length > 0">
            <el-tag 
              v-for="accessory in scope.row.accessories" 
              :key="accessory.id"
              size="mini"
              style="margin: 2px;"
            >
              {{ accessory.accessory_name }}
            </el-tag>
          </div>
          <div v-else style="color: #999; font-size: 12px;">无配件</div>
        </template>
      </el-table-column>
      <el-table-column label="收货人" width="100px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.contract && scope.row.contract.recipient_name">{{ scope.row.contract.recipient_name }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人手机号" width="130px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.contract && scope.row.contract.recipient_tel">{{ scope.row.contract.recipient_tel }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" min-width="200px">
        <template slot-scope="scope">
          <span v-if="scope.row.contract && scope.row.contract.recipient_address">{{ scope.row.contract.recipient_address }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      <el-table-column prop="track_number" label="物流单号" width="150px"></el-table-column>
      <el-table-column prop="status" label="订单状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="160px" align="center">
        <template slot-scope="scope">
          {{ formatTime(scope.row.update_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" min-width="120px">
        <template slot-scope="scope">
          <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
          <span v-else style="color: #999;">无</span>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column label="操作" width="120px" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="handleDeleteOrder(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 修改订单弹窗 -->
    <el-dialog
      title="修改订单"
      :visible.sync="editDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px">
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择订单状态" style="width: 100%;">
            <el-option label="生产中" :value="1">
              <el-tag type="warning" size="mini">生产中</el-tag>
            </el-option>
            <el-option label="已发货" :value="2">
              <el-tag type="primary" size="mini">已发货</el-tag>
            </el-option>
            <el-option label="已签收" :value="3">
              <el-tag type="success" size="mini">已签收</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="track_number">
          <el-input v-model="editForm.track_number" placeholder="请输入物流单号"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="editForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="editLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteOrder, getOrderList, changeOrderStatus } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'OrderManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      statusFilter: '', // 状态筛选
      
      // 表格数据
      orderList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 修改弹窗相关
      editDialogVisible: false,
      editForm: {
        id: '',
        status: '',
        track_number: '',
        remark: ''
      },
      editRules: {
      },
      editLoading: false
    };
  },
  methods: {
    async handleDeleteOrder(order) {
      try {
        await this.$confirm(`确定要删除该订单吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const response = await deleteOrder(order.id);
        
        if (response.data && response.data.code) {
          this.$message.success('删除订单成功');
          // 重新加载订单列表
          this.fetchOrderList(  );
        } else {
          this.$message.error(response.data.msg || '删除订单失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除订单失败:', error);
          this.$message.error('删除订单失败');
        }
      }
    },
    // 获取订单列表
    async fetchOrderList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          keyword: this.searchKeyword,
          status: this.statusFilter, // 添加状态筛选参数
          page: this.currentPage,
          pageSize: this.pageSize
        };
        
        const response = await getOrderList(params);
        
        if (response.data && response.data.code) {
          // API成功返回数据
          this.orderList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取订单列表失败');
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        if (checkTokenFromError(error)) {
          // Token无效或过期
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          // 其他错误
          this.$message.error('获取订单列表失败');
        }
      } finally {
        this.loading = false;
      }
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '-';
      const date = new Date(timestamp * 1000);
      return date.toLocaleString('zh-CN');
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchOrderList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.statusFilter = ''; // 重置状态筛选
      this.currentPage = 1;
      this.fetchOrderList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchOrderList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchOrderList();
    },

    // 打开修改弹窗
    handleEdit(row) {
      this.editForm = { ...row }; // 复制当前行数据到编辑表单
      this.editDialogVisible = true;
    },

    // 提交修改
    async submitEdit() {
      this.$refs.editForm.validate(async (valid) => {
        if (valid) {
          this.editLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const params = {
              id: this.editForm.id,
              status: this.editForm.status,
              track_number: this.editForm.track_number,
              remark: this.editForm.remark
            };

            const response = await changeOrderStatus(params); // 假设 $api 是全局或通过 props 传递的 API 对象

            if (response.data && response.data.code) {
              this.$message.success('订单修改成功');
              this.editDialogVisible = false;
              this.fetchOrderList(); // 刷新列表
            } else {
              this.$message.error(response.data.msg || '订单修改失败');
            }
          } catch (error) {
            console.error('提交订单修改失败:', error);
            if (checkTokenFromError(error)) {
              // Token无效或过期
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              // 其他错误
              this.$message.error('提交订单修改失败');
            }
          } finally {
            this.editLoading = false;
          }
        }
      });
    },

    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 1:
          return 'warning'; // 生产中
        case 2:
          return 'primary'; // 已发货
        case 3:
          return 'success'; // 已签收
        default:
          return '';
      }
    },

    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 1:
          return '生产中';
        case 2:
          return '已发货';
        case 3:
          return '已签收';
        default:
          return '未知';
      }
    }
  },
  
  created() {
    this.fetchOrderList();
  }
};
</script>

<style scoped>
.order-management-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

/* 状态标签样式 */
.el-tag {
  font-weight: 500;
}
</style> 